﻿using Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.Models;
using Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.VisualStudio;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.Utilities
{
    public static class FxCopCmdOptionBuilder
    {
        public static string Build(Solution solution)
        {
            var result = new List<string>();
            result.Add("/p:" + '"' + solution.FxCopProjectPath + '"');
            result.Add("/o:" + '"' + Path.Combine(solution.CodeAnalysisDirectoryPath, "CodeAnalysisReport.xml") + '"');

            if (File.Exists(solution.FxCopDictionaryPath))
            {
                result.Add("/dic:" + '"' + solution.FxCopDictionaryPath + '"');
            }

            return String.Join<string>(" ", result);
        }

        public static string Build(Project project, Version version)
        {
            var config = CodeAnalysisConfiguration.Load(project.ConfigurationPath);
            config.Override(CodeAnalysisConfiguration.Load(project.Solution.ConfigurationPath));

            var result = new List<string>();

            result.Add("/f:" + '"' + project.AssemblyPath + '"');
            result.Add("/o:" + '"' + Path.Combine(project.TargetDir, "CodeAnalysisReport.xml") + '"');
            result.Add("/q");
            result.Add("/sf");
            result.Add("/to:" + ((config.Timeout > 0) ? Convert.ToInt32(config.Timeout) : 0));

            if (config.EnableSearchGac)
            {
                result.Add("/gac");
            }

            if (config.IgnoreGeneratedCode)
            {
                result.Add("/igc");
            }

            if (version.Major >= 10)
            {
                if (File.Exists(config.RuleSet))
                {
                    result.Add("/rs:=" + '"' + config.RuleSet + '"');
                }
            }

            if (File.Exists(project.Solution.FxCopDictionaryPath))
            {
                result.Add("/dic:" + '"' + project.Solution.FxCopDictionaryPath + '"');
            }

            foreach (var dir in project.DependencyDirectories)
            {
                result.Add("/d:" + '"' + dir + '"');
            }

            return String.Join<string>(" ", result);
        }
    }
}
